<template>
	<view class="mask">
		<view class="header">
			答题卡
			<view class="close-btn" @click="close"> <uni-icons type="closeempty" size="20"></uni-icons></view>
		</view>
		<view class="status">
			<text class="title">状态说明:</text>
			<view class="circular green" />
			<text class="sub-title">正确</text>
			<view class="circular red" />
			<text class="sub-title">错误</text>
		</view>
		<view class="main">
			<view class="title"> 一、单选题（本大题共{{ singleList.length }}小题，共{{ getTotalScore(singleList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in singleList"
					:class="{ green: isCorrect(item), red: isError(item) }" :key="item.questionId"
					@click="link(item.navIndex)">{{ index + 1 }}</view>
			</view>
			<view class="title">二、多选题（本大题共{{ multipleList.length }}小题，共{{ getTotalScore(multipleList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in multipleList"
					:class="{ green: isCorrect(item), red: isError(item) }" :key="item.questionId"
					@click="link(item.navIndex)">{{ (singleList.length || 0) + index + 1 }}</view>
			</view>
			<view class="title">三、判断题（本大题共{{ judgementList.length }}小题，共{{ getTotalScore(judgementList) }}分）</view>
			<view class="circular-box">
				<view class="circular white" v-for="(item,index) in judgementList"
					:class="{ green: isCorrect(item), red: isError(item) }" :key="item.questionId"
					@click="link(item.navIndex)">{{ (singleList.length || 0) + (multipleList.length || 0) + index + 1}}
				</view>
			</view>
		</view>
		<view class="footer" v-if="!isView">
			<view class="submit" @click="tipDialogVisible = true">提交试卷</view>
		</view>
		<tip-dialog v-model="tipDialogVisible" @confirm="handleSubmit" :type="noDoneNum ? '' : 'primary'"
			:examType="type">
			<view>{{ noDoneNum ? '温馨提示' : '恭喜您' }}</view>
			<view>{{ noDoneNum ? `您还有${noDoneNum}题未做，确认交卷吗` : '题目已全部答完，确认交卷吗' }}</view>
		</tip-dialog>
		<examination-dialog v-model="examinationDialogVisible" :status="examinationDialogStatus"
			:data="examinationResult" @ended="handleEnded" />
	</view>
</template>

<script>
	import {
		getSimulationTestDetail
	} from '@/api/educational-training/simulation-test.js'
	import {
		getExaminationList,
		getAppExaminationRecord
	} from '@/api/educational-training/examination.js'
	import {
		mapMutations,
		mapState,
		mapActions
	} from 'vuex'
	import {
		get,
		sum
	} from 'lodash'
	import TipDialog from "../online-examination/components/TipDialog";
	import ExaminationDialog from "../online-examination/components/ExaminationDialog";
	import {
		examinationStatus
	} from '@/utils/constant'
	import {
		handin,
		saveTestRecord
	} from "../../../api/educational-training/examination";

	export default {
		name: 'answer-sheet',
		components: {
			TipDialog,
			ExaminationDialog,
		},
		data() {
			return {
				id: null,
				simulationId: null, // 模拟id
				paperData: {
					judgementList: [],
					multipleList: [],
					singleList: []
				},
				mode: '', // view 查看
				type: '', // ''.正常考试 1.题库训练 2.模拟考试
				typeId: '', // examinationTypeId
				tipDialogVisible: false,
				examinationDialogVisible: false,
				examinationDialogStatus: examinationStatus.PAUSE,
				examinationResult: {},
				urlParams: {},
				uuid: '' // 模拟训练随机出题返回的uuid
			}
		},
		onLoad({
			id,
			simulationId,
			mode,
			type,
			uuid,
			data
		}) {
			this.id = id
			this.simulationId = simulationId
			this.mode = mode
			this.type = type
			this.typeId = id

			if (type == '2') {
				let dataObj = JSON.parse(data)
				this.urlParams = dataObj
				this.count = dataObj.count
				this.uuid = uuid
			}
		},

		onShow() {
			this.fetchData()
		},

		computed: {
			...mapState({
				examDetailList: (state) => state.onlineExam.examDetailList
			}),
			isView() {
				return this.mode === 'view'
			},
			singleList() {
				return get(this.paperData, 'singleList', []).map((item, index) => ({
					...item,
					navIndex: index
				}))
			},
			multipleList() {
				return get(this.paperData, 'multipleList', []).map((item, index) => ({
					...item,
					navIndex: index + this.singleList.length
				}))
			},
			noDoneNum() {
				return this.examDetailList.filter(item => !item.selectOptionIds.length).length
			},
			judgementList() {
				return get(this.paperData, 'judgementList', []).map((item, index) => ({
					...item,
					navIndex: index + this.singleList.length + this.multipleList.length
				}))
			}
		},
		methods: {
			...mapActions(['submitPapel']),
			...mapMutations(['setCurrentPaperIndex']),
			async fetchData() {
				if (this.isView) {
					{
						const {
							data,
							code
						} = await getSimulationTestDetail(this.id)
						this.paperData = data
						let singleList = []
						let multipleList = []
						let judgementList = []
						for (let i of this.paperData.questionTypes) {
							i.type = i.questionType
							if (i.type === '1') {
								for (let j of i.questionList) {
									j.score = i.score
									j.totalNum = i.totalNum
									j.totalScore = i.totalScore
									j.type = i.type
									let correctIds = []
									for (let p of j.optionList) {
										if (p.rightFlag === 'Y') {
											correctIds.push(p.id)
										}
									}
									j.correctOptionIds = correctIds
									singleList.push(j)

								}

							} else if (i.type === '2') {
								for (let j of i.questionList) {
									j.score = i.score
									j.totalNum = i.totalNum
									j.totalScore = i.totalScore
									j.type = i.type
									let correctIds = []
									for (let p of j.optionList) {
										if (p.rightFlag === 'Y') {
											correctIds.push(p.id)
										}
									}
									j.correctOptionIds = correctIds
									multipleList.push(j)
								}

							} else {
								for (let j of i.questionList) {
									j.score = i.score
									j.totalNum = i.totalNum
									j.totalScore = i.totalScore
									j.type = i.type
									let correctIds = []
									for (let p of j.optionList) {
										if (p.rightFlag === 'Y') {
											correctIds.push(p.id)
										}
									}
									j.correctOptionIds = correctIds
									judgementList.push(j)
								}
							}
						}
						this.paperData.singleList = singleList
						this.paperData.multipleList = multipleList
						this.paperData.judgementList = judgementList
					}
				}
			},
			async getExamList(type, id) {
				let params = {
					examinationTypeId: id
				}
				let res
				// type = 1 ，题库训练
				if (type == 1) {
					res = await getExaminationList(params)
					this.paperData = res.data
				}
				// type = 2 ，模拟考试
				if (type == 2) {
					res = await getAppExaminationRecord({
						uuid: this.uuid
					})
					// 先清空
					this.paperData = {
						judgementList: [],
						multipleList: [],
						singleList: []
					}
					// 每题分数带过来
					const {
						singleScore,
						multipleScore,
						judgementScore
					} = this.urlParams
					res.data.map(item => {
						if (item.exercisesType === '1') {
							item.score = singleScore
							this.paperData.singleList.push(item)
						} else if (item.exercisesType === '2') {
							item.score = multipleScore
							this.paperData.multipleList.push(item)
						} else if (item.exercisesType === '3') {
							item.score = judgementScore
							this.paperData.judgementList.push(item)
						}
					})
				}
			},
			getTotalScore(list) {
				return sum(list.map((item) => item.score))
			},
			close() {
				uni.navigateBack()
			},
			isCorrect(item) {
				if (this.isView) {
					if (item.selectOptionIds.length !== item.correctOptionIds.length) {
						return false
					}
					return item.selectOptionIds.every((ele) => item.correctOptionIds.includes(ele));
				} else {
					return get(this.examDetailList, `${navIndex}.selectOptionIds.length`, 0)
				}
			},
			isError(item) {
				return !this.isCorrect(item)
			},
			link(index) {
				this.setCurrentPaperIndex(index)
				this.close()
			},
			async handleSubmit() {
				console.log('examDetailList', this.examDetailList)
				// 题库训练
				if (this.type == 1) {
					let temp = []
					this.examDetailList.map(e => {
						if (e.selectOptionIds.length === 0) return
						temp.push({
							choseOptions: e.selectOptionIds.join(','),
							examinationId: e.examinationId,
							exerciseType: e.exerciseType,
						})
					})
					saveTestRecord({
						examinationTypeId: this.typeId,
						detailList: temp,
					}).then(res => {
						uni.navigateTo({
							url: `/pages/work/online-examination/train-result?type=${this.type}&id=${this.typeId}`
						})
					})
				}
				// 模拟训练
				if (this.type == 2) {
					let arr = []
					this.examDetailList.map(item => {
						if (item.selectOptionIds.length === 0) return
						arr.push({
							choseOptions: item.selectOptionIds.join(','),
							examinationId: item.examinationId,
							examinationTypeId: Number(this.typeId),
							exerciseType: item.exerciseType,
						})
					})
					let params = {
						...this.urlParams,
						detailList: arr,
						examinationTypeId: this.typeId,
					}
					handin(params).then(({
						data
					}) => {
						if (data.score < this.urlParams.passmark) {
							this.examinationDialogStatus = examinationStatus.FAIL
						} else {
							this.examinationDialogStatus = examinationStatus.SUCCESS
						}
						this.examinationResult = {
							score: data.score,
							errors: data.wrongCount,
							no_answer: data.unansweredCount,
							qualifying: this.urlParams.passmark,
						}
						this.examinationDialogVisible = true
					})
				}
			},
			handleEnded() {
				uni.navigateBack({
					delta: 2
				})
			},
		}
	}
</script>

<style scoped lang="scss" type="text/scss">
	.mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding-top: 50rpx;
}
.header {
  position: relative;
  height: 88rpx;
  line-height: 88rpx;
  width: 100%;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  text-align: center;

  .close-btn {
    position: absolute;
    top: 0;
    left: 30rpx;
  }
}
.status {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  height: 77rpx;
  padding-left: 30rpx;
  background: #f5f5f5;

  .title {
    color: #333333;
    margin-right: 10rpx;
  }
  .sub-title {
    color: #666666;
    margin-right: 30rpx;
  }
  .circular {
    margin-right: 10rpx;
  }
}
.circular {
  width: 34rpx;
  height: 34rpx;
  border-radius: 50%;
}
.white {
  background: #ffffff;
  border: 1px solid #bbbbbb;
  color: #999999;
}
.green {
  background: #ebf2f5;
  border: 1px solid #59c416;
  color: #0cc437;
}
.red {
  color: #A14430;
  background: #EFDEDB;
  border: 1px solid #A14430;
}
.main {
	overflow: auto;
	height: calc(100vh - 400rpx);
  padding: 30rpx 10rpx 40rpx;

  .circular {
    width: 90rpx;
    height: 90rpx;
    margin-left: 30rpx;
    margin-top: 30rpx;
    text-align: center;
    line-height: 90rpx;
  }
  .circular-box {
    display: flex;
		flex-wrap: wrap;
    margin-bottom: 50rpx;
  }
}
.footer {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  .submit {
    text-align: center;
    width: 600rpx;
    height: 98rpx;
    line-height: 98rpx;
    font-size: 36rpx;
    color: #ffffff;
    background: #454a5e;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
  }
}
</style>
